<template>
  <el-container>
    <el-header class="home_header">
      <div class="home_header_logo">
        <img class="logo" src="@/assets/icon/scnx_logo.png" alt="" />
        <span class="title">全网收单后台管理系统</span>
      </div>
      <div class="home_header_oper">
        <div v-for="item in operates" :key="item.id" class="oper_icon" @click="clickOper(item)">
          <el-badge :value="item.badgeNum" class="item" v-if="item.badgeFlag">
            <el-tooltip class="box-item" effect="dark" :content="item.title" placement="bottom">
              <el-image :src="item.icon"></el-image>
            </el-tooltip>
          </el-badge>
          <el-tooltip v-else class="box-item" effect="dark" :content="item.title" placement="bottom">
              <el-image :src="item.icon"></el-image>
            </el-tooltip>
        </div>
        <div class="oper_icon">
          <el-tooltip class="box-item" effect="dark" :content="`${userInfo.userName}-${userInfo.dept.deptName}-${userInfo.role.roleName}`" placement="bottom">
            <el-image :src="user"></el-image>
          </el-tooltip>
        </div>
        <div>
          {{ userInfo.userName }}
        </div>
      </div>
    </el-header>
    <el-container>
      <el-aside width="220px" class="home_aside">
        <el-scrollbar class="home_aside_scrollbar">
          <MainMenu :menuInfos="menuList" @change="onChangeMenu"></MainMenu>
        </el-scrollbar>
      </el-aside>
      <el-main class="home_container">
        <el-tabs v-model="checkedTab.tabName" class="home_tab_content" closable @tab-remove="removeTab"
          @tab-change="tabChange">
          <el-tab-pane :key="-1" label="首页" name="首页&joint&Desktop">
            <el-scrollbar class="home_scrollbar">
              <component :is="Desktop" ref="homeRefComponent" :params="checkedTab.params" class="home_component" />
            </el-scrollbar>
          </el-tab-pane>
          <el-tab-pane v-for="item in homeTabs" :key="item.menuId" :label="item.menuName"
            :name="item.menuName + '&joint&' + item.menuPath.split('/')[item.menuPath.split('/').length - 1]">
            <el-scrollbar class="home_scrollbar">
              <component :is="item.component" :ref="item.menuPath" :params="item.params" class="home_component" />
            </el-scrollbar>
          </el-tab-pane>
        </el-tabs>
        <div class="more_tab" v-if="homeTabs.length > 2">
          <span>更多<el-icon style="vertical-align: middle; margin-left: 4px">
              <ArrowDown />
            </el-icon></span>
          <div class="more_content">
            <el-scrollbar height="200px">
              <div class="open_tab_item" @click="closeTab('ALL')">
                关闭全部
              </div>
              <div class="open_tab_item" v-for="(item, index) in homeTabs" :key="index">
                <span @click="tabChangeMore(item)">{{
                  item.menuName
                  }}</span>
                <el-icon @click="closeTab(item)">
                  <Close />
                </el-icon>
              </div>
            </el-scrollbar>
          </div>
        </div>
      </el-main>
    </el-container>
  </el-container>
</template>

<script lang="ts" setup>
/** 全局引入 */
import {
  ref,
  reactive,
  computed,
  onMounted,
  onUnmounted,
  watch,
  onBeforeMount,
  inject,
  defineAsyncComponent,
} from "vue";
import { Close, ArrowDown } from "@element-plus/icons-vue";
import { ElLoading } from 'element-plus'
import MainMenu from "@/components/MainMenu.vue";
import Desktop from "@/views/pub/Desktop.vue";
import icon0 from '@/assets/icon/header_0.png';
import icon1 from '@/assets/icon/header_1.png';
import icon2 from '@/assets/icon/header_2.png';
import icon3 from '@/assets/icon/header_3.png';
import icon4 from '@/assets/icon/header_4.png';
import user from '@/assets/icon/user.png';
const operates = reactive([
  {
    id: 'header_oper_0',
    icon: icon0,
    title: '导入记录查询',
    badgeFlag: false,
    badgeNum: 0,
    url: 'ListImportRecordInquiry',
  },
  {
    id: 'header_oper_1',
    icon: icon1,
    title: '待审核事项',
    badgeFlag: true,
    badgeNum: 9,
    url: 'toDoTaskList',
  },
  {
    id: 'header_oper_2',
    icon: icon2,
    title: '已审核事项',
    badgeFlag: true,
    badgeNum: 9,
    url: 'completedTaskList',
  },
  {
    id: 'header_oper_3',
    icon: icon3,
    title: '常见问题',
    badgeFlag: false,
    badgeNum: 0,
    url: 'question',
  },
  {
    id: 'header_oper_4',
    icon: icon4,
    title: '退出登录',
    badgeFlag: false,
    badgeNum: 0,
    url: 'outlogin',
  },
])
const $request: any = inject("$request");
const $pageFiles: any = inject("$pageFiles");
const $utils: any = inject("$utils");
import { storeToRefs } from "pinia";
import { usePiniaStore } from "@/pinia/index.ts"
const pinia = usePiniaStore();
const { userInfo } = storeToRefs(pinia);
import { homeStore } from '@/pinia/homeStore.ts';
const homePinia = homeStore();
let { homeTabs, checkedTab } = storeToRefs(homePinia);


/** 定义数据 */
const loading = ElLoading.service({
  lock: true,
  text: 'Loading',
  customClass: 'custom-loading',
  background: 'rgba(0, 0, 0, 0.7)',
})
$utils.initDicts().then(() => {
  loading.close()
})
  .catch(() => {
    loading.close()
  });
//字段类型
interface MenuItem {
  menuId: number;
  menuPath: string;
  menuName: string;
  submenus?: MenuItem[];
  menuType: string;
  parentId: number;
  menuIcon: string;
}
// 数组数据
const menuList = ref<MenuItem[]>([]);
const message = ref("");
homeTabs = reactive(homeTabs);
checkedTab = reactive(checkedTab);
/** 侦听 */
watch(
  homeTabs,
  (newValue, oldValue) => {
    homePinia.changeHomeTabs(newValue);
  },
  { deep: true }
);
watch(
  checkedTab,
  (newValue, oldValue) => {
    homePinia.changeCheckedTab(newValue);
  },
  { deep: true }
);

/** 计算 */
/** 方法 */
const getMenuDatas = () => {
  const action = {
    userId: userInfo.value.userId,
  };
  $request
    .rpc({ name: "protect.user.GetUserMenus", action })
    .then((result: any) => {
      menuList.value = result.list;
    })
    .catch(() => { });
};
/** 选择菜单 */
const onChangeMenu = (data: any) => {
  const pathSegments = data.menuPath.split("/");
  const path = pathSegments[pathSegments.length - 1];
  openPage(data.menuName, path, {});
};
/** 移除tab页 */
const removeTab = (el: any) => {
  homeTabs.value = homeTabs.value.filter((item) => {
    const pathSegments = item.menuPath.split("/");
    const path = pathSegments[pathSegments.length - 1];
    // 返回布尔值，判断是否要保留该项
    return item.menuName + "&joint&" + path !== el; // 如果 path 与 el 相等，则移除该项
  });
  if (el == checkedTab.value.tabName) {
    homePinia.changeCheckedTab({
      tabName: "首页&joint&Desktop",
      compontentName: $pageFiles.Desktop,
      params: {},
    });
  }
};
/** 关闭tab页面（自定义） */
const closeTab = (item: any) => {
  if (item == "ALL") {
    homeTabs.value = [];
    homePinia.changeCheckedTab({
      tabName: "首页&joint&Desktop",
      compontentName: $pageFiles.Desktop,
      params: {},
    });
  } else {
    const pathSegments = item.menuPath.split("/");
    const path = pathSegments[pathSegments.length - 1];
    const val = item.menuName + "&joint&" + path;
    removeTab(val);
  }
};
/** 选择tab页 */
const tabChange = (el: any) => {
  let tabName = "";
  homeTabs.value.forEach((item) => {
    const pathSegments = item.menuPath.split("/");
    const path = pathSegments[pathSegments.length - 1];
    item.menuName + "&joint&" + path === el ? (tabName = item.menuName) : "";
  });
  const componentNames = el.split("&joint&");
  const componentName = componentNames[componentNames.length - 1];
  openPage(tabName, componentName, {});
};
/** 选择tab */
const tabChangeMore = (el: any) => {
  openPage(el.menuName, el.menuPath, {});
};

/** 打开页面 */
const openPage = (title: string, component: string, params: any) => {
  homePinia.openTabPage(title, component, params);
};

/** 点击操作按钮 */
const clickOper = (item: any) => {
  console.log(item)
  if(item.url == 'outlogin') {
    $utils.closeDialogGoToLogin();
  } else if(item.url == 'question') {
    console.log('常见问题')
  } else {
    homePinia.openTabPage(item.title, item.url, { data: '我是传递的params数据' })
  }
}
/** 生命周期钩子 */
onBeforeMount(() => {
  getMenuDatas();
});
onMounted(() => {
  // console.log("挂载完成Home.vue");
});
onUnmounted(() => {
  // console.log("销毁完成Home.vue");
});
</script>
<style lang="scss" scoped>
@use "@/styles/home.scss";
</style>
